<template>
  <div class="chat-container">
    <div class="message-list" ref="messageList">
      <pre>{{ message }}</pre>
    </div>
    <div class="input-container">
      <input
          v-model="inputMessage"
          type="text"
          placeholder="输入咨询内容"
          @keyup.enter="getStreamData"
      />
      <button @click="getStreamData" v-loading="loading">发送</button>
    </div>
  </div>
</template>

<script setup>
import {ref, nextTick} from 'vue'

const message = ref('')
const inputMessage = ref('')
const loading = ref(false)
const messageList = ref(null)

async function getStreamData() {
  try {
    if (!inputMessage.value.trim()) return

    loading.value = true
    message.value = ''

    const response = await fetch('/api/ai', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: inputMessage.value
    })


    if (!response.ok) throw new Error('请求失败')
    if (!response.body) throw new Error('无响应体')

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    while (true) {
      const {done, value} = await reader.read()
      if (done) break

      // 处理流数据
      const chunk = decoder.decode(value)
      const jsonStr = chunk.replace('data:', '');
      console.log(chunk.trim()+'-----------'+jsonStr.trim())
      // console.log(data.result.output.content)
      message.value += jsonStr.trim()

      // 自动滚动到底部
      await nextTick()
      messageList.value.scrollTo({
        top: messageList.value.scrollHeight,
        behavior: 'smooth'
      })
    }
  } catch (error) {
    console.error('请求出错:', error)
    message.value += '\n[请求出错，请重试]'
  } finally {
    loading.value = false
    inputMessage.value = ''
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.chat-container {
  width: 80%;
  margin: 0 auto;
}

.message-list {
  height: 400px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap; /* 保留换行 */
  word-break: break-word; /* 自动换行 */
}

.input-container {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

/* 其他样式保持不变 */
</style>